﻿@inherits NITASA.Views.AutofacEnabledViewPage<NITASA.Data.Content>
@using NITASA.Services.Security
@using NITASA.Data
@using NITASA.Areas.Admin.Helper
@{
    ViewBag.Title = "Update Post";
    Meta meta = ViewBag.meta;
}

@section PageLevelStyles{
    <style type="text/css">
        #slug-container {
            color: #666;
            line-height: 24px;
            margin-top: 5px;
            min-height: 25px;
            padding: 0 10px;
        }

        strong {
            font-weight: 600;
        }

        #slug-container {
            color: #666;
            line-height: 24px;
        }

        .editable-container span {
            background-color: #fffbcc;
        }

        .editable-container input {
            font-size: 13px;
            height: 22px;
            margin: 0;
            width: 16em;
        }

        .slug-buttons .button-small {
            border-color: #ccc;
            border-radius: 3px;
            border-style: solid;
            border-width: 1px;
            color: #555;
            cursor: pointer;
            font-size: 13px;
            line-height: 18px;
            padding: 0 10px 1px;
        }

        .slug-buttons .cancel {
            font-size: 11px;
            margin-right: 10px;
        }
    </style>
    <script src="@Url.Content("~/Areas/Admin/assets/js/tinymce/tinymce.min.js")"></script>
    <script type="text/javascript">
        var popuptype = "cover";
        $ext = 'span[id|name|class|style]';
        tinyMCE.init({
            selector: ".edtr",
            theme: "modern",
            menubar: false,
            plugins: [
                "advlist autolink lists link image charmap preview hr anchor",
                "searchreplace wordcount visualblocks visualchars code fullscreen",
                "insertdatetime nonbreaking save table contextmenu directionality",
                "emoticons template paste textcolor colorpicker textpattern "
            ],
            toolbar1: "undo redo | styleselect | forecolor backcolor | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link | Variables | mediaimages | code | Addons",
            image_advtab: false,
            extended_valid_elements: $ext,
            force_br_newlines: false,
            force_p_newlines: false,
            forced_root_block: '',
            setup: function (editor) {
                editor.addButton('mediaimages', {
                    text: '',
                    title: 'Insert image',
                    icon: 'mce-ico mce-i-image',
                    onclick: function () {
                        popuptype = "editor";
                        $("#MediaPopup").modal('show');
                    }
                });
            }
        });
    </script>
}
<div class="main-content">
    <div class="container-fluid padded">
        @if (TempData["ErrorMessage"] != null)
        {
            <div class="alert alert-error">
                <button class="close" data-dismiss="alert" type="button">
                    ×
                </button>
                @TempData["ErrorMessage"]
            </div>
        }
        <div id="containerfluid"></div>
        <div class="row-fluid">
            <div class="span12">
                <div class="box">
                    <div class="box-header">
                        <span class="title"><i class="icon-book"></i>&nbsp; Edit Post</span>
                        <div class="span4 title pull-right" style="float:right;margin-right:10px;"><div class="inline pull-right">Status : @(Model.isPublished?"Published":"Draft")</div></div>
                    </div>
                    <div class="box-content">
                        <div class="padded">
                            <div class="span12">
                                @using (Html.BeginForm("Edit", "Post", FormMethod.Post, new { id = "frm1" }))
                                {
                                    <div class="span9">
                                        <div class="control-group">
                                            <div class="controls">
                                                <input type="hidden" id="UpdateType" name="UpdateType" />
                                                @Html.TextBoxFor(mbox => mbox.Title, new { placeholder = "Post Title", @class = "width100per", style = "margin-bottom: 0px;" })
                                                <div style="color: red">
                                                    @Html.ValidationMessageFor(m => m.Title)
                                                </div>
                                                <div>
                                                    <div id="slug-container">
                                                        <strong>Permalink:</strong>
                                                        <span>@(Request.Url.AbsoluteUri.Replace(Request.Url.AbsolutePath, ""))/Content/
                                                            <span class="editable-container" style=" margin-left: -3px;">
                                                                <span id="editable-slug">@Model.URL</span>
                                                                <input type="text" value="@Model.URL" id="edit-slug-text" style="display: none;" />
                                                            </span>
                                                        </span>&lrm;
                                                        <span class="slug-buttons">
                                                            <a id="edit-slug" class="button-small"
                                                               href="#">Edit</a>
                                                            <a id="save-slug" class="button-small" href="#" style="display: none;">OK</a>
                                                            <a href="#" id="cancel-slug" class="cancel" style="display: none;">Cancel</a>
                                                            <a href="#" id="pagePreview" class="button-small">Preview</a>
                                                        </span>
                                                        @Html.HiddenFor(m => m.URL)
                                                        @Html.CheckBoxFor(m => m.IsSlugEdited, new { style = "display:none;" })
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="control-group">
                                            <div class="controls">
                                                <label>
                                                    <b>Post Description: </b>
                                                </label>
                                                <div>
                                                    @Html.TextAreaFor(m => m.Description, new { @class = "edtr", style = "width: 100%; max-width: 98%; height:500px; margin: 0px; overflow: hidden; word-wrap: break-word;resize:vertical;" })
                                                    @*@class = "textarea-html5", *@
                                                    <div style="color: red">
                                                        @Html.ValidationMessageFor(m => m.Description)
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="span3">
                                        <div class="padded" style="padding: 0px 4px 13px 4px; ">
                                            @if (Functions.CurrentUserID() == Model.AddedBy)
                                            {
                                                if (aclService.HasRight(Rights.PublishOwnPosts))
                                                {
                                                    <input type="button" class="btn btn-small btn-green" id="btnPost" style="text-align: center; width: 60px;"
                                                           value="Publish" />
                                                }
                                            }
                                            else
                                            {
                                                if (aclService.HasRight(Rights.PublishOtherUsersPosts))
                                                {
                                                    <input type="button" class="btn btn-small btn-green" id="btnPost" style="text-align: center; width: 60px;"
                                                           value="Publish" />
                                                }
                                            }&nbsp;
                                            <input type="button" class="btn btn-small btn-blue" style="text-align: center; width: 90px; " value="Save to Draft"
                                                   id="btnSaveToDraft" />&nbsp;
                                            <input type="button" class="btn btn-small btn-red" style="text-align: center; width: 60px;" value="Back"
                                                   onclick="window.location = '/Admin/Post/List';" />
                                        </div>
                                        <div class="box">
                                            <div class="box-header">
                                                <span class="title">Labels</span>
                                            </div>
                                            <div class="box-content">
                                                <div class="padded">
                                                    @Html.DropDownList("LabelId", (List<SelectListItem>)ViewBag.Labellist, new { @class = "select2-container select2-container-multi chzn-select", multiple = "multiple", id = "ddlLabels" })
                                                    <input id="txtNewLabel" type="text" maxlength="40" placeholder="New Label" style="margin-bottom: 0px;
                                                        width: 84% !important;" />&nbsp;
                                                    <a data-toggle="modal" title="Add New Label" id="btnAddLabel" href="#">
                                                        <i class="icon-plus-sign" style="font-size: 20px; vertical-align:middle"></i>
                                                    </a>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="box">
                                            <div class="box-header">
                                                <span class="title">Categories</span>
                                            </div>
                                            <div class="box-content">
                                                <div class="padded">
                                                    <select name="CategoryId" id="CategoryId" multiple="multiple" data-val-required="Please select category."
                                                            data-val="true" class="select2-container select2-container-multi chzn-select">
                                                        @foreach (SelectListItem item in (IEnumerable<SelectListItem>)ViewBag.Categorylist)
                                                        {
                                                            <option value="@item.Value" selected="@item.Selected">@item.Text</option>
                                                        }
                                                    </select>
                                                    <div style="color: red">
                                                        <span data-valmsg-replace="true" data-valmsg-for="CategoryId" class="field-validation-valid">
                                                        </span>
                                                    </div>
                                                    <input id="txtNewCategory" name="txtNewCategory" type="text" maxlength="40" placeholder="New Category" style="margin-bottom: 0px;
                                                        width: 84% !important;" />&nbsp;
                                                    <a data-toggle="modal" title="Add New Category" id="btnAddCategory" href="#">
                                                        <i class="icon-plus-sign" style="font-size: 20px; vertical-align:middle"></i>
                                                    </a>
                                                </div>
                                            </div>
                                        </div>

                                        <div class="box">
                                            <div class="box-header">
                                                <span class="title">Meta</span>
                                            </div>
                                            <div class="box-content">
                                                <div class="padded">
                                                    <input type="text" id="txtMetaTitle" name="txtMetaTitle" placeholder="Title" class="width100per" value="@meta.Title" />
                                                    <input type="text" id="txtMetaKeyword" name="txtMetaKeyword" placeholder="Keyword" class="width100per" value="@meta.Keyword" />
                                                    <input type="text" id="txtMetaDescription" name="txtMetaDescription" placeholder="Description" class="width100per" value="@meta.Description" />
                                                    <input type="text" id="txtMetaAuthor" name="txtMetaAuthor" placeholder="Author Name" class="width100per" value="@meta.Author" />
                                                </div>
                                            </div>
                                        </div>
                                        <div class="box">
                                            <div class="box-header">
                                                <span class="title">Display Order</span>
                                            </div>
                                            <div class="box-content">
                                                <div class="padded" style="text-align:left;vertical-align:top">
                                                    @Html.TextBoxFor(mbox => mbox.ContentOrder, new { placeholder = "Content Order To Display", style = "margin-bottom: 0px;" })
                                                    <div style="color: red">
                                                        @Html.ValidationMessageFor(m => m.ContentOrder)
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="box">
                                            <div class="box-header">
                                                <span class="title">Comment Setting</span>
                                            </div>
                                            <div class="box-content">
                                                <div class="padded">
                                                    <div class="control-label">
                                                        @Html.CheckBoxFor(m => m.EnableComment, new { style = "float:left;margin-top:4px;" })
                                                        <label for="EnableComment" style="margin-left:20px;">Comment Enabled ?</label>
                                                        <label for="ddlEnableTill">Enable Comment Till </label>
                                                        @Html.DropDownListFor(m => m.CommentEnabledTill,
                                                            new List<SelectListItem>() {
                                                                new SelectListItem { Text = "15 Days", Value = "15"},
                                                                new SelectListItem { Text = "1 Month", Value = "30" },
                                                                new SelectListItem { Text = "6 Months", Value = "180" },
                                                                new SelectListItem { Text = "Always", Value = "36000" }
                                                            })
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="box">
                                            <div class="box-header">
                                                <span class="title">Cover Content</span>
                                            </div>
                                            <div class="box-content">
                                                <div class="padded" style="text-align: left; vertical-align: top">
                                                    <label>
                                                        <b>Content: </b>
                                                    </label>
                                                    @Html.TextAreaFor(m => m.CoverContent, new { style = "height:100px;width:98%;" })
                                                    <div style="text-align: center; margin-top:10px;">
                                                        <label style="display:inline;">
                                                            <b>Image: </b>
                                                        </label>
                                                        @Html.HiddenFor(m => m.FeaturedImage)
                                                        <input type="button" id="btnBImage" class="btn btn-small btn-blue" style="text-align: center; width: 80px;" value="Select" />
                                                        <input type="button" id="btnBRemove" class="btn btn-small btn-red" style="text-align: center; width: 80px;" value="Remove" />
                                                    </div>
                                                    <div style="text-align: center; margin-top:10px;">
                                                        @if (Model != null)
                                                        {
                                                            <img id="uploadedImage" style="max-height: 200px; max-width: 200px;" src="@Model.FeaturedImage" />
                                                        }
                                                        else
                                                        {
                                                            <img id="uploadedImage" style="max-height: 200px; max-width: 200px;" />
                                                        }
                                                    </div>
                                                </div>
                                            </div>
                                        </div>

                                    </div>
                                }
                            </div>
                            &nbsp;
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

@{Html.RenderAction("GetMedia", "Media", new { isEditor = true });}

@section BottomScript{
    <script type="text/javascript">
        $(document).ready(function () {
            $("#edit-slug").click(function () {
                $("#editable-slug").css("display", "none");
                $("#edit-slug-text").css("display", "");
                $("#edit-slug").css("display", "none");
                $("#save-slug").css("display", "");
                $("#cancel-slug").css("display", "");
            });
            $("#cancel-slug").click(function () {
                $("#edit-slug-text").val($("#editable-slug").html());
                $("#editable-slug").css("display", "");
                $("#edit-slug-text").css("display", "none");
                $("#edit-slug").css("display", "");
                $("#save-slug").css("display", "none");
                $("#cancel-slug").css("display", "none");
            });
            $("#save-slug").click(function () {
                $("#URL").val($("#edit-slug-text").val().trim());
                $("#editable-slug").css("display", "");
                $("#editable-slug").html($("#edit-slug-text").val().trim());
                $("#edit-slug-text").css("display", "none");
                $("#edit-slug").css("display", "");
                $("#save-slug").css("display", "none");
                $("#cancel-slug").css("display", "none");
            });
            $("#EnableComment").on("change", function () {
                if ($(this).is(":checked"))
                    $("#CommentEnabledTill").attr("disabled", false);
                else
                    $("#CommentEnabledTill").attr("disabled", true);
            });
            $("#EnableComment").trigger("change");
            $("#btnAddLabel").click(function () {
                if ($.trim($("#txtNewLabel").val()).length > 0) {

                    if (ValidateRegex($("#txtNewLabel").val())) {
                        var currLabel = $.trim($("#txtNewLabel").val());
                        $.ajax({
                            type: "POST",
                            url: '/Admin/Post/AddLabel',
                            data: { labelName: currLabel },
                            dataType: "json",
                            success: function (data) {
                                if (data != false) {
                                    $("#ddlLabels").append("<option value=\"" + data + "\" selected=\"true\">" + currLabel + "</option>");
                                    $("#ddlLabels").trigger('change');
                                    $("#txtNewLabel").val("");
                                }
                                else {
                                    $("#ddlLabels option").each(function () {
                                        if ($(this).text().toLowerCase() == currLabel.toLowerCase()) {
                                            $(this).attr('selected', 'selected');
                                        }
                                    });
                                    $("#ddlLabels").trigger('change');
                                    $("#txtNewLabel").val("");
                                }
                            }
                            //error: function (data) { alert(data); }
                        });
                        //$("#ddlLabels").val(["Facebook", "Orkut", "Pinterest"]).trigger('change');
                    }
                    else {
                        alert("Only alpha numeric and special characters like '_ , . , # , & , * , + , - '  are allowed");
                    }
                }
                else {
                    $("#txtNewLabel").val("");
                    alert("Please enter label text");
                }
                return false;
            });
            $("#btnAddCategory").click(function () {

                if ($.trim($("#txtNewCategory").val()).length > 0) {
                    if (ValidateRegex($("#txtNewCategory").val())) {
                        var currCat = $.trim($("#txtNewCategory").val());
                        $.ajax({
                            type: "POST",
                            url: '/Admin/Post/AddCategory',
                            data: { CategoryName: currCat },
                            dataType: "json",
                            success: function (data) {
                                if (data != false) {
                                    $("#CategoryId").append("<option value=\"" + data + "\" selected=\"true\">" + currCat + "</option>");
                                    $("#CategoryId").trigger('change');
                                    $("#txtNewCategory").val("");
                                }
                                else {
                                    $("#CategoryId option").each(function () {
                                        if ($(this).text().toLowerCase() == currCat.toLowerCase()) {
                                            $(this).attr('selected', 'selected');
                                        }
                                    });
                                    $("#CategoryId").trigger('change');
                                    $("#txtNewCategory").val("");
                                }
                            }
                            //error: function (data) { alert(data); }
                        });
                        //$("#ddlLabels").val(["Facebook", "Orkut", "Pinterest"]).trigger('change');
                    }
                    else {
                        alert("Only alpha numeric and special characters like '_ , . , # , & , * , + , - '  are allowed");
                    }
                }
                else {
                    $("#txtNewCategory").val("");
                    alert("Please enter category name");
                }

                return false;
            });
            $('#btnPost').click(function () {
                $("#UpdateType").val("Publish");
                tinyMCE.triggerSave();
                if (validpost()) {
                    $('#frm1').submit();
                }
            });

            $('#btnSaveToDraft').click(function () {
                $("#UpdateType").val("SaveToDraft");
                tinyMCE.triggerSave();
                if (validpost()) {
                    $('#frm1').submit();
                }
            });
            function validpost() {
                if ($("#frm1").valid()) {
                    return true;
                }
                else {
                    var error = '<div class="alert alert-error"><button class="close" data-dismiss="alert" type="button">×</button>Please solve form errors</div>';
                    $("#containerfluid").html(error);
                }
            }
            $('#btnBRemove').click(function () {
                $('#FeaturedImage').val("");
                $('#uploadedImage').attr("src", "");
                $('#uploadedImage').css("display", "none");
            });

            $('#btnBImage').click(function (e) {
                e.preventDefault();
                popuptype = "cover";
                $('#MediaPopup').modal("show");
            });
            $("body").delegate(".wizard-input-section .media-thumb .imgSelect", "click", function () {
                var imgPath = $(this).attr('src');
                if (popuptype == "cover") {
                    $('#FeaturedImage').val(imgPath);
                    $('#uploadedImage').attr("src", imgPath);
                    $('#uploadedImage').css("display", "");
                }
                else {   //editor
                    var url = imgPath;
                    var img = "<img src=\"" + url + "\"/>";
                    tinyMCE.activeEditor.execCommand('mceInsertContent', false, img);
                }
                $("#MediaPopup").modal("hide");
            });
            $('#pagePreview').click(function () {
                tinyMCE.triggerSave();
                if (validpost()) {
                    var str = $( "#frm1" ).serialize();    
                    console.log(str);
                    var slug = $("#URL").val();
                    $.ajax({
                        type: "POST",
                        url: "@Url.Action("Preview", "Post")",
                        data: str,
                    success: function (data) {
                        if (data == "success") {
                            //alert(data);
                            window.open('/Content/Details?prv=true&URL='+slug, "_blank");
                        }
                    },
                    error: function (data) {
                        alert('Sorry. Unable to Preview !!');
                    }
                });
            }
            });
        });
    </script>
}
